from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.db.models import Q
from .models import Asset
from .forms import AssetForm
from django.core.paginator import Paginator

# 原有的视图函数需要重新添加回来
@login_required
def asset_list_mine(request):
    """我的设备列表"""
    # 搜索功能
    search_query = request.GET.get('search', '')
    
    assets = Asset.objects.filter(assigned_to=request.user)
    
    if search_query:
        assets = assets.filter(
            Q(name__icontains=search_query) |
            Q(model__icontains=search_query) |
            Q(serial_number__icontains=search_query)
        )
    
    # 统计信息
    stats = {
        'total': Asset.objects.filter(assigned_to=request.user).count(),
        'active': Asset.objects.filter(assigned_to=request.user, status='active').count(),
        'maintenance': Asset.objects.filter(assigned_to=request.user, status='maintenance').count(),
        'retired': Asset.objects.filter(assigned_to=request.user, status='retired').count(),
    }
    
    # 按类型统计
    type_stats = {}
    for type_code, type_name in Asset.TYPE_CHOICES:
        count = Asset.objects.filter(assigned_to=request.user, asset_type=type_code).count()
        if count > 0:
            type_stats[type_name] = count
    
    context = {
        'assets': assets,
        'search_query': search_query,
        'stats': stats,
        'type_stats': type_stats
    }
    return render(request, 'assets/list_mine.html', context)

@login_required
def asset_create(request):
    """创建设备"""
    if request.method == 'POST':
        form = AssetForm(request.POST)
        if form.is_valid():
            asset = form.save(commit=False)
            asset.save()
            messages.success(request, '设备创建成功！')
            return redirect('assets:asset_list_mine')
        else:
            messages.error(request, '请修正以下错误：')
    else:
        form = AssetForm()
    
    return render(request, 'assets/create.html', {'form': form})

@login_required
def asset_detail(request, pk):
    """设备详情"""
    asset = get_object_or_404(Asset, pk=pk)
    context = {
        'asset': asset
    }
    return render(request, 'assets/detail.html', context)

@login_required
def asset_edit(request, pk):
    """编辑设备"""
    asset = get_object_or_404(Asset, pk=pk)
    if request.method == 'POST':
        # 这里需要实现编辑设备的逻辑
        pass
    context = {
        'asset': asset
    }
    return render(request, 'assets/edit.html', context)

@login_required
def asset_update_status(request, pk):
    """更新设备状态"""
    asset = get_object_or_404(Asset, pk=pk)
    if request.method == 'POST':
        # 这里需要实现更新状态的逻辑
        pass
    return redirect('assets:asset_detail', pk=asset.pk)

@login_required
def asset_manage(request):
    """设备管理 - 管理员功能"""
    if not request.user.is_staff:
        messages.error(request, '您没有权限访问设备管理')
        return redirect('dashboard')
    
    # 搜索功能
    search_query = request.GET.get('search', '')
    status_filter = request.GET.get('status', '')
    category_filter = request.GET.get('category', '')
    
    assets = Asset.objects.all().select_related('assigned_to')
    
    if search_query:
        assets = assets.filter(
            Q(name__icontains=search_query) |
            Q(code__icontains=search_query) |
            Q(model__icontains=search_query) |
            Q(assigned_to__username__icontains=search_query) |
            Q(assigned_to__first_name__icontains=search_query) |
            Q(assigned_to__last_name__icontains=search_query)
        )
    
    if status_filter:
        assets = assets.filter(status=status_filter)
    
    if category_filter:
        assets = assets.filter(category=category_filter)
    
    # 分页
    paginator = Paginator(assets.order_by('-created_at'), 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'assets': page_obj,
        'search_query': search_query,
        'status_filter': status_filter,
        'category_filter': category_filter,
        'status_choices': Asset.STATUS_CHOICES,
        'category_choices': Asset.TYPE_CHOICES,
    }
    return render(request, 'assets/manage.html', context)

@login_required
def asset_admin_detail(request, pk):
    """设备详情 - 管理员视图"""
    if not request.user.is_staff:
        messages.error(request, '您没有权限查看设备详情')
        return redirect('dashboard')
    
    asset = get_object_or_404(Asset.objects.select_related('assigned_to'), pk=pk)
    
    context = {
        'asset': asset,
        'status_choices': Asset.STATUS_CHOICES,
        'category_choices': Asset.TYPE_CHOICES,
    }
    return render(request, 'assets/admin_detail.html', context)

@login_required
def asset_admin_edit(request, pk):
    """编辑设备信息 - 管理员功能"""
    if not request.user.is_staff:
        messages.error(request, '您没有权限编辑设备信息')
        return redirect('dashboard')
    
    asset = get_object_or_404(Asset.objects.select_related('assigned_to'), pk=pk)
    
    if request.method == 'POST':
        try:
            asset.name = request.POST.get('name', asset.name)
            asset.code = request.POST.get('code', asset.code)
            asset.model = request.POST.get('model', asset.model)
            asset.asset_type = request.POST.get('asset_type', asset.asset_type)
            asset.status = request.POST.get('status', asset.status)
            asset.serial_number = request.POST.get('serial_number', asset.serial_number)
            
            # 处理日期字段
            purchase_date = request.POST.get('purchase_date')
            asset.purchase_date = purchase_date if purchase_date else asset.purchase_date
            
            warranty_expiry = request.POST.get('warranty_expiry')
            asset.warranty_expiry = warranty_expiry if warranty_expiry else asset.warranty_expiry
            
            # 处理价格字段
            purchase_price = request.POST.get('purchase_price')
            asset.purchase_price = purchase_price if purchase_price else asset.purchase_price
            
            # 处理位置信息
            asset.department = request.POST.get('department', asset.department)
            asset.location = request.POST.get('location', asset.location)
            asset.notes = request.POST.get('notes', asset.notes)
            
            # 处理分配用户 - 只允许分配给客户
            assigned_to_username = request.POST.get('assigned_to')
            if assigned_to_username:
                from django.contrib.auth.models import User
                try:
                    user = User.objects.get(username=assigned_to_username)
                    # 验证用户角色是否为客户
                    if hasattr(user, 'profile') and user.profile.role == 'customer':
                        asset.assigned_to = user
                    else:
                        messages.error(request, f'只能将设备分配给客户角色，用户 {assigned_to_username} 不是客户')
                        asset.assigned_to = None
                except User.DoesNotExist:
                    messages.error(request, f'用户 {assigned_to_username} 不存在')
                    asset.assigned_to = None
            else:
                asset.assigned_to = None
            
            asset.save()
            messages.success(request, f'设备 {asset.name} 信息更新成功')
            return redirect('assets:asset_admin_detail', pk=asset.pk)
            
        except Exception as e:
            messages.error(request, f'更新设备信息失败: {str(e)}')
    
    # 只获取客户角色的用户用于设备分配
    from django.contrib.auth.models import User
    users = User.objects.filter(profile__role='customer')
    
    context = {
        'asset': asset,
        'users': users,
        'status_choices': Asset.STATUS_CHOICES,
        'category_choices': Asset.TYPE_CHOICES,
    }
    return render(request, 'assets/admin_edit.html', context)

@login_required
def asset_admin_update_status(request, pk):
    """更新设备状态 - 管理员功能"""
    if not request.user.is_staff:
        messages.error(request, '您没有权限更新设备状态')
        return redirect('dashboard')
    
    asset = get_object_or_404(Asset, pk=pk)
    
    if request.method == 'POST':
        new_status = request.POST.get('status')
        if new_status in dict(Asset.STATUS_CHOICES):
            asset.status = new_status
            asset.save()
            messages.success(request, f'设备 {asset.name} 状态已更新为 {asset.get_status_display()}')
        else:
            messages.error(request, '无效的设备状态')
    
    return redirect('assets:asset_admin_detail', pk=asset.pk)
